<template>
  <div class="video-list">
    <div class="page-header">
      <h1>管廊系统视频列表</h1>
      <div class="header-actions">
        <t-button theme="primary" @click="handleAdd">
          <template #icon><t-icon name="add" /></template>
          添加视频源
        </t-button>
        <t-input
          v-model="searchText"
          placeholder="搜索视频"
          style="width: 200px; margin-left: 16px"
          clearable
        >
          <template #suffix-icon>
            <t-icon name="search" @click="onSearch" />
          </template>
        </t-input>
      </div>
    </div>

    <t-tabs v-model="activeTab" :list="tabList" @change="handleTabChange" />

    <div class="view-toggle">
      <t-radio-group v-model="viewMode">
        <t-radio-button value="grid">
          <template #default>
            <t-icon name="view-module" />
            网格视图
          </template>
        </t-radio-button>
        <t-radio-button value="list">
          <template #default>
            <t-icon name="view-list" />
            列表视图
          </template>
        </t-radio-button>
      </t-radio-group>
    </div>

    <!-- 网格视图 -->
    <div v-if="viewMode === 'grid'" class="video-grid">
      <t-card
        v-for="video in filteredVideos"
        :key="video.id"
        :hover-shadow="true"
        class="video-card"
      >
        <template #cover>
          <div class="video-thumbnail" @click="handlePlay(video)">
            <img :src="video.thumbnail" :alt="video.name" />
            <div class="play-icon">
              <t-icon name="play-circle-filled" size="48px" />
            </div>
            <t-tag class="status-tag" :theme="getStatusTheme(video.status)" variant="light">
              {{ video.status }}
            </t-tag>
          </div>
        </template>
        <template #title>
          <div class="video-title">{{ video.name }}</div>
        </template>
        <template #description>
          <div class="video-info">
            <div class="info-item">
              <t-icon name="location" />
              <span>{{ video.location }}</span>
            </div>
            <div class="info-item">
              <t-icon name="time" />
              <span>{{ video.lastUpdateTime }}</span>
            </div>
          </div>
        </template>
        <template #actions>
          <t-space>
            <t-button theme="primary" variant="text" @click="handlePlay(video)">
              <template #icon><t-icon name="play-circle" /></template>
              播放
            </t-button>
            <t-button theme="primary" variant="text" @click="handleEdit(video)">
              <template #icon><t-icon name="edit" /></template>
              编辑
            </t-button>
            <t-button theme="danger" variant="text" @click="showDeleteConfirm(video)">
              <template #icon><t-icon name="delete" /></template>
              删除
            </t-button>
          </t-space>
        </template>
      </t-card>
    </div>

    <!-- 列表视图 -->
    <t-table
      v-else
      :columns="columns"
      :data="filteredVideos"
      :loading="loading"
      :pagination="{ pageSize: 10 }"
      bordered
      row-key="id"
    >
      <template #thumbnail="{ row }">
        <div class="table-thumbnail" @click="handlePlay(row)">
          <img :src="row.thumbnail" :alt="row.name" />
          <div class="play-icon-small">
            <t-icon name="play-circle-filled" />
          </div>
        </div>
      </template>
      <template #status="{ row }">
        <t-tag :theme="getStatusTheme(row.status)" variant="light">
          {{ row.status }}
        </t-tag>
      </template>
      <template #op="{ row }">
        <t-space>
          <t-link theme="primary" hover="color" @click="handlePlay(row)">播放</t-link>
          <t-link theme="primary" hover="color" @click="handleEdit(row)">编辑</t-link>
          <t-link theme="danger" hover="color" @click="showDeleteConfirm(row)">删除</t-link>
        </t-space>
      </template>
    </t-table>

    <!-- 添加/编辑视频对话框 -->
    <t-dialog
      v-model:visible="modalVisible"
      :header="modalTitle"
      :confirm-loading="confirmLoading"
      @confirm="handleModalOk"
    >
      <t-form
        ref="formRef"
        :data="formState"
        :rules="rules"
        :label-width="100"
      >
        <t-form-item label="视频名称" name="name">
          <t-input v-model="formState.name" />
        </t-form-item>
        <t-form-item label="视频类型" name="type">
          <t-select v-model="formState.type">
            <t-option value="实时监控" label="实时监控" />
            <t-option value="录像回放" label="录像回放" />
            <t-option value="报警视频" label="报警视频" />
          </t-select>
        </t-form-item>
        <t-form-item label="视频源" name="source">
          <t-input v-model="formState.source" />
        </t-form-item>
        <t-form-item label="所属设备" name="deviceId">
          <t-select v-model="formState.deviceId">
            <t-option v-for="device in cameraDevices" :key="device.id" :value="device.id" :label="device.name" />
          </t-select>
        </t-form-item>
        <t-form-item label="安装位置" name="location">
          <t-input v-model="formState.location" />
        </t-form-item>
        <t-form-item label="视频状态" name="status">
          <t-select v-model="formState.status">
            <t-option value="在线" label="在线" />
            <t-option value="离线" label="离线" />
            <t-option value="故障" label="故障" />
          </t-select>
        </t-form-item>
        <t-form-item label="备注" name="remark">
          <t-textarea v-model="formState.remark" :rows="3" />
        </t-form-item>
      </t-form>
    </t-dialog>

    <!-- 视频播放对话框 -->
    <t-dialog
      v-model:visible="playerVisible"
      header="视频播放"
      :footer="false"
      width="800px"
      destroy-on-close
    >
      <div v-if="currentVideo" class="video-player">
        <div class="player-header">
          <h3>{{ currentVideo.name }}</h3>
          <div class="video-info-bar">
            <span class="info-item">
              <t-icon name="location" />
              {{ currentVideo.location }}
            </span>
            <span class="info-item">
              <t-icon name="time" />
              {{ currentVideo.lastUpdateTime }}
            </span>
            <t-tag :theme="getStatusTheme(currentVideo.status)" variant="light">
              {{ currentVideo.status }}
            </t-tag>
          </div>
        </div>
        <div class="player-container">
          <!-- 这里可以集成真实的视频播放器组件 -->
          <div class="player-placeholder">
            <img :src="currentVideo.thumbnail" :alt="currentVideo.name" />
            <div class="player-overlay">
              <t-icon name="play-circle-filled" size="64px" />
              <p>此处可集成实际的视频播放器组件</p>
            </div>
          </div>
        </div>
        <div class="player-controls">
          <t-space>
            <t-button theme="primary">
              <template #icon><t-icon name="play-circle" /></template>
              播放
            </t-button>
            <t-button>
              <template #icon><t-icon name="pause-circle" /></template>
              暂停
            </t-button>
            <t-button>
              <template #icon><t-icon name="stop-circle" /></template>
              停止
            </t-button>
            <t-button>
              <template #icon><t-icon name="screenshot" /></template>
              截图
            </t-button>
            <t-button>
              <template #icon><t-icon name="download" /></template>
              下载
            </t-button>
          </t-space>
        </div>
      </div>
    </t-dialog>

    <!-- 删除确认对话框 -->
    <t-dialog
      v-model:visible="deleteConfirmVisible"
      header="确认删除"
      body="确定要删除这个视频源吗?"
      @confirm="confirmDelete"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import dayjs from 'dayjs';

// 表格列定义
const columns = [
  {
    colKey: 'thumbnail',
    title: '缩略图',
    width: '120',
    cell: 'thumbnail',
  },
  {
    colKey: 'name',
    title: '视频名称',
    width: '150',
  },
  {
    colKey: 'type',
    title: '视频类型',
    width: '100',
  },
  {
    colKey: 'location',
    title: '安装位置',
    width: '150',
  },
  {
    colKey: 'deviceId',
    title: '所属设备',
    width: '150',
    cell: ({ row }) => row.deviceId ? getDeviceName(row.deviceId) : '-',
  },
  {
    colKey: 'status',
    title: '视频状态',
    width: '100',
    cell: 'status',
  },
  {
    colKey: 'lastUpdateTime',
    title: '最后更新',
    width: '150',
  },
  {
    colKey: 'op',
    title: '操作',
    width: '180',
    cell: 'op',
  },
];

// 标签页定义
const tabList = [
  { value: 'all', label: '全部' },
  { value: 'realtime', label: '实时监控' },
  { value: 'playback', label: '录像回放' },
  { value: 'alarm', label: '报警视频' },
];

// 摄像头设备数据
const cameraDevices = ref([
  { id: 'D001', name: '入口摄像头' },
  { id: 'D006', name: '出口摄像头' },
  { id: 'D007', name: '中段摄像头A' },
  { id: 'D008', name: '中段摄像头B' },
]);

// 模拟数据
const videos = ref([
  {
    id: 'V001',
    name: '入口实时监控',
    type: '实时监控',
    source: 'rtsp://192.168.1.101/live',
    deviceId: 'D001',
    location: '管廊入口',
    status: '在线',
    lastUpdateTime: '2023-09-20 14:30:45',
    thumbnail: 'https://placeholder.pics/svg/300x200/DEDEDE/555555/入口监控',
    remark: '入口区域实时监控画面',
  },
  {
    id: 'V002',
    name: '出口实时监控',
    type: '实时监控',
    source: 'rtsp://192.168.1.105/live',
    deviceId: 'D006',
    location: '管廊出口',
    status: '在线',
    lastUpdateTime: '2023-09-20 14:28:12',
    thumbnail: 'https://placeholder.pics/svg/300x200/DEDEDE/555555/出口监控',
    remark: '出口区域实时监控画面',
  },
  {
    id: 'V003',
    name: '中段A实时监控',
    type: '实时监控',
    source: 'rtsp://192.168.1.107/live',
    deviceId: 'D007',
    location: '管廊中段A区',
    status: '离线',
    lastUpdateTime: '2023-09-19 09:15:33',
    thumbnail: 'https://placeholder.pics/svg/300x200/DEDEDE/555555/中段A监控',
    remark: '中段A区域实时监控画面',
  },
  {
    id: 'V004',
    name: '中段B实时监控',
    type: '实时监控',
    source: 'rtsp://192.168.1.108/live',
    deviceId: 'D008',
    location: '管廊中段B区',
    status: '故障',
    lastUpdateTime: '2023-09-18 10:45:22',
    thumbnail: 'https://placeholder.pics/svg/300x200/DEDEDE/555555/中段B监控',
    remark: '中段B区域实时监控画面',
  },
  {
    id: 'V005',
    name: '入口昨日录像',
    type: '录像回放',
    source: 'http://192.168.1.200/recordings/D001/20230919',
    deviceId: 'D001',
    location: '管廊入口',
    status: '在线',
    lastUpdateTime: '2023-09-19 23:59:59',
    thumbnail: 'https://placeholder.pics/svg/300x200/DEDEDE/555555/入口录像',
    remark: '入口区域昨日全天录像',
  },
  {
    id: 'V006',
    name: '出口昨日录像',
    type: '录像回放',
    source: 'http://192.168.1.200/recordings/D006/20230919',
    deviceId: 'D006',
    location: '管廊出口',
    status: '在线',
    lastUpdateTime: '2023-09-19 23:59:59',
    thumbnail: 'https://placeholder.pics/svg/300x200/DEDEDE/555555/出口录像',
    remark: '出口区域昨日全天录像',
  },
  {
    id: 'V007',
    name: '入口报警事件',
    type: '报警视频',
    source: 'http://192.168.1.200/alarms/D001/20230918-143022',
    deviceId: 'D001',
    location: '管廊入口',
    status: '在线',
    lastUpdateTime: '2023-09-18 14:30:22',
    thumbnail: 'https://placeholder.pics/svg/300x200/DEDEDE/555555/入口报警',
    remark: '入口区域检测到异常活动的报警视频',
  },
]);

const loading = ref(false);
const searchText = ref('');
const activeTab = ref('all');
const viewMode = ref('grid');
const modalVisible = ref(false);
const modalTitle = ref('添加视频源');
const confirmLoading = ref(false);
const formRef = ref(null);
const currentId = ref(null);
const playerVisible = ref(false);
const currentVideo = ref(null);
const deleteConfirmVisible = ref(false);
const videoToDelete = ref(null);

// 表单状态
const formState = reactive({
  name: '',
  type: '实时监控',
  source: '',
  deviceId: '',
  location: '',
  status: '在线',
  remark: '',
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入视频名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择视频类型', trigger: 'change' }],
  source: [{ required: true, message: '请输入视频源地址', trigger: 'blur' }],
  deviceId: [{ required: true, message: '请选择所属设备', trigger: 'change' }],
  location: [{ required: true, message: '请输入安装位置', trigger: 'blur' }],
  status: [{ required: true, message: '请选择视频状态', trigger: 'change' }],
};

// 根据标签页和搜索条件过滤视频
const filteredVideos = computed(() => {
  let result = [...videos.value];
  
  // 按标签页筛选
  if (activeTab.value !== 'all') {
    const typeMap = {
      realtime: '实时监控',
      playback: '录像回放',
      alarm: '报警视频',
    };
    result = result.filter(video => video.type === typeMap[activeTab.value]);
  }
  
  // 按搜索文本筛选
  if (searchText.value) {
    const keyword = searchText.value.toLowerCase();
    result = result.filter(
      (video) =>
        video.name.toLowerCase().includes(keyword) ||
        video.location.toLowerCase().includes(keyword) ||
        video.type.toLowerCase().includes(keyword) ||
        video.id.toLowerCase().includes(keyword)
    );
  }
  
  return result;
});

// 获取设备名称
const getDeviceName = (deviceId) => {
  const device = cameraDevices.value.find(d => d.id === deviceId);
  return device ? device.name : '-';
};

// 获取视频状态对应的主题色
const getStatusTheme = (status) => {
  switch (status) {
    case '在线': return 'success';
    case '离线': return 'default';
    case '故障': return 'danger';
    default: return 'default';
  }
};

// 搜索处理
const onSearch = () => {
  // 搜索逻辑已通过计算属性实现
};

// 标签页切换处理
const handleTabChange = (value) => {
  activeTab.value = value;
};

// 添加视频
const handleAdd = () => {
  resetForm();
  modalTitle.value = '添加视频源';
  modalVisible.value = true;
  currentId.value = null;
};

// 编辑视频
const handleEdit = (row) => {
  modalTitle.value = '编辑视频源';
  modalVisible.value = true;
  currentId.value = row.id;
  
  // 填充表单数据
  formState.name = row.name;
  formState.type = row.type;
  formState.source = row.source;
  formState.deviceId = row.deviceId;
  formState.location = row.location;
  formState.status = row.status;
  formState.remark = row.remark;
};

// 播放视频
const handlePlay = (row) => {
  currentVideo.value = { ...row };
  playerVisible.value = true;
};

// 显示删除确认对话框
const showDeleteConfirm = (row) => {
  videoToDelete.value = row;
  deleteConfirmVisible.value = true;
};

// 确认删除视频
const confirmDelete = () => {
  if (videoToDelete.value) {
    videos.value = videos.value.filter(item => item.id !== videoToDelete.value.id);
    MessagePlugin.success('视频源已删除');
    videoToDelete.value = null;
  }
};

// 模态框确认
const handleModalOk = () => {
  formRef.value.validate().then((result) => {
    if (result === true) {
      confirmLoading.value = true;
      
      setTimeout(() => {
        if (currentId.value) {
          // 更新视频
          const index = videos.value.findIndex(item => item.id === currentId.value);
          if (index !== -1) {
            videos.value[index] = {
              ...videos.value[index],
              name: formState.name,
              type: formState.type,
              source: formState.source,
              deviceId: formState.deviceId,
              location: formState.location,
              status: formState.status,
              remark: formState.remark,
              lastUpdateTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            };
            MessagePlugin.success('视频源已更新');
          }
        } else {
          // 添加视频
          const lastId = videos.value.length > 0 
            ? parseInt(videos.value[videos.value.length - 1].id.substring(1)) 
            : 0;
          const newId = `V${(lastId + 1).toString().padStart(3, '0')}`;
          
          videos.value.push({
            id: newId,
            name: formState.name,
            type: formState.type,
            source: formState.source,
            deviceId: formState.deviceId,
            location: formState.location,
            status: formState.status,
            remark: formState.remark,
            lastUpdateTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            thumbnail: 'https://placeholder.pics/svg/300x200/DEDEDE/555555/新视频',
          });
          MessagePlugin.success('视频源已添加');
        }
        
        modalVisible.value = false;
        confirmLoading.value = false;
      }, 500);
    }
  }).catch(error => {
    console.log('验证失败:', error);
  });
};

// 重置表单
const resetForm = () => {
  formState.name = '';
  formState.type = '实时监控';
  formState.source = '';
  formState.deviceId = '';
  formState.location = '';
  formState.status = '在线';
  formState.remark = '';
  
  // 重置表单验证状态
  if (formRef.value) {
    formRef.value.reset();
  }
};

// 生命周期钩子
onMounted(() => {
  // 这里可以添加从API获取视频列表的逻辑
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
  }, 500);
});
</script>

<style scoped>
.video-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
}

.view-toggle {
  margin: 16px 0;
  display: flex;
  justify-content: flex-end;
}

.video-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.video-card {
  transition: all 0.3s;
}

.video-thumbnail {
  position: relative;
  height: 180px;
  overflow: hidden;
  cursor: pointer;
}

.video-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  opacity: 0;
  transition: opacity 0.3s;
  color: white;
  text-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}

.video-thumbnail:hover .play-icon {
  opacity: 1;
}

.status-tag {
  position: absolute;
  top: 10px;
  right: 10px;
}

.video-title {
  font-weight: 500;
}

.video-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #666;
  font-size: 14px;
}

.table-thumbnail {
  width: 100px;
  height: 60px;
  position: relative;
  overflow: hidden;
  cursor: pointer;
}

.table-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.play-icon-small {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  opacity: 0;
  transition: opacity 0.3s;
  color: white;
  text-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
}

.table-thumbnail:hover .play-icon-small {
  opacity: 1;
}

.video-player {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.player-header {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.video-info-bar {
  display: flex;
  align-items: center;
  gap: 16px;
}

.player-container {
  width: 100%;
  height: 450px;
  background-color: #000;
  position: relative;
}

.player-placeholder {
  width: 100%;
  height: 100%;
  position: relative;
}

.player-placeholder img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.player-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
}

.player-controls {
  padding: 16px 0;
}
</style> 